<template>
  <view class="lookback-details-main">
    <view>
      <view @click="checkIndex = 0" :class="checkIndex === 0 ? 'lookback-details-check' : ''">图片展示</view>
      <view @click="checkIndex = 1" :class="checkIndex === 1 ? 'lookback-details-check' : ''">视频展示</view>
    </view>

    <view>{{activityData.activityName}}</view>

    <view>
      <view v-if="checkIndex === 0">
        <rich-text :nodes="repairRichText(activityData.contentText)"></rich-text>
      </view>

      <view v-if="checkIndex === 1">
        <video
            style="width: 100%; border-radius: 10px;"
            :src="activityData.contentVideo"
            controls
            autoplay
            loop>
        </video>

        <view v-if="activityData.contentVideo" class="lookback-details-save-btn" @click="saveVideo">保存视频</view>
      </view>
    </view>

    <button open-type="share">分享</button>
  </view>
</template>

<script setup>
import {getActivityRecalldetailApi} from "@/api/activity"
import {ref } from "vue"
import {onShareAppMessage, onShareTimeline, onShow} from "@dcloudio/uni-app"
import {
  getUrlParamsInH5,
  getUrlParamsInWeixin,
  rpx2px,
  wxSetUpShareFunction,
} from "../../../utils/utils"

let activityData = ref({}), activityId = ref(), isShare = ref(0)


onShareAppMessage(()=>{
  return {
    title:activityData.value.activityName,
    path:`/package_activity/pages/activity/activity-lookback-details?isShare=1&id=${activityData.value.activityId}`,
    imageUrl:activityData.value.activityPoster
  }
})

onShareTimeline(()=>{
  return {
    title:activityData.value.activityName,
    imageUrl:activityData.value.activityPoster
  }
})

onShow(async () => {
  /* #ifdef MP-WEIXIN */
  activityId.value = getUrlParamsInWeixin()?.id;
  isShare.value = getUrlParamsInWeixin()?.isShare
  wxSetUpShareFunction();
  /* #endif */
  /* #ifdef H5 */
  activityId.value = getUrlParamsInH5()?.id;
  isShare.value = getUrlParamsInH5()?.isShare
  /* #endif */

  const {code, data} = await getActivityRecalldetailApi(activityId.value)
  if (code === 200) {
    activityData.value = data
  }
})

let checkIndex = ref(0)

const repairRichText = (html) => {
  // 去掉<img>中style /width / height属性
  let newContent = html.replace(/<img[^>]*>/gi, (match) => {
    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '')
    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '')
    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '')
    match = match.replace(/style\s*=\s*(["'])(?:(?!\1).)*\1/gi, '') // 去除 style=""这样的属性
    return match
  })
  // 修改所有style里的width属性为max-width:100%
  newContent = newContent.replace(/style="[^"]+"/gi, (match) => {
    match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi,
        'max-width:100%;')
    return match
  })

  // 去掉所有<br/>标签
  newContent = newContent.replace(/<br[^>]*\/>/gi, '')
  // img标签添加style属性：max-width:100%;height:auto
  newContent = newContent.replace(/\<img/gi,
      '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"'
  )
  return newContent;
}

const saveVideo = () => {
  let url = activityData.value.contentVideo

  uni.showLoading({
    title: '保存中...',
    mask: true // 可选参数，设置为true时阻止用户操作
  })
  //提前发起授权申请
  wx.authorize({
    scope: 'scope.writePhotosAlbum',
    success: res => {
      console.log("授权成功---");
      wx.getSetting({
        withSubscriptions: true,
        success: res => {
          console.info(res.authSetting);
          if (res.authSetting['scope.writePhotosAlbum']) {
            wx.downloadFile({
              url,
              header: {
                'content-type': 'application/json'
              },

              success: res => {
                console.log(res, '成功');
                uni.showToast({
                  icon: "none",
                  title: "视频已保存到相册"
                })
                //保存到相册
                wx.saveVideoToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success: res => {

                    uni.showToast({
                      icon: "none",
                      title: "视频已保存到相册"
                    })
                    uni.hideLoading();
                  },
                  fail: err => {
                    console.log(err, 'err');
                    uni.showToast({
                      icon: "none",
                      title: "保存失败"
                    })
                    uni.hideLoading();
                  }
                })
              }
            });

          } else {
            uni.hideLoading();
            wx.showModal({
              cancelColor: 'cancelColor',
              title: '提示',
              content: '请开启相册访问权限',
              success: res => {
                if (res.confirm)
                  wx.openSetting({
                    withSubscriptions: true,
                  })
              }
            })
          }
        }
      })

    },
    fail: res => {
      wx.showToast({
        title: '拒绝授权后，请点击授权相册',
      })

    }
  })
}
</script>

<style lang="less">
.ql-align-center {
  text-align: center;
}

.lookback-details-main {
  padding: 10px;
  background-color: #ffffff;
  height: 100%;
  font-size: 14px;

  >view:nth-child(1) {
    background-color: #e6e6e9;
    border-radius: 10px;
    margin-top: 10px;

    >view {
      display: inline-block;
      width: 50%;
      text-align: center;
      height: 30px;
      line-height: 30px;
      box-shadow: #eae8e8 0 0 10px 1px;
      border-radius: 10px;
    }
  }

  >view:nth-child(2) {
    text-align: center;
    margin-top: 10px;
  }

  >view:nth-child(3) {
    padding: 10px;
  }

  >button:nth-child(4) {
    text-align: center;
    background-color: #01a7f0;
    color: #ffffff;
    border-radius: 20px;
    width: calc(100% - 20px);
    height: 30px;
    line-height: 30px;
    position: fixed;
    left: 10px;
    bottom: 30px;
  }
}

.lookback-details-check {
  background-color: #ffffff;
}

.lookback-details-save-btn {
  width: 150px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-radius: 20px;
  border: 1px solid #01a7f0;
  color: #01a7f0;
  margin: 20px auto;
}
</style>
